﻿using System;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web;
using DeGiglio.biz.Twitter.Properties;

namespace DeGiglio.biz.Twitter.Classes
{
    internal static class Common
    {
        /// <summary>
        /// Use this property to get the locale ID of the current thread. This can be called from user controls or web parts 
        /// but should *not* be called from web services.
        /// </summary>
        internal static int LocaleID
        {
            get
            {
                return System.Globalization.CultureInfo.CurrentUICulture.LCID;
            }
        }

        /// <summary>
        /// Use this method to gather a localized string from the project resx file(s). This is for localizing strings from within code
        /// </summary>
        /// <param name="keyName">The key of the value in the resx file to be returned</param>
        /// <param name="localeId">The locale ID of the language to return</param>
        /// <returns>The localized value from the resx file</returns>
        internal static string GetResourceValue(string keyName, int localeId)
        {
            CultureInfo userCulture = new CultureInfo(localeId);
            return HttpContext.GetGlobalResourceObject(ProjectSettings.Default.ResourceFileName, keyName, userCulture).ToString();
        }

        internal static T DeserializeJson<T>(string json)
        {
            var obj = Activator.CreateInstance<T>();
            using (var memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(json)))
            {
                var serializer = new DataContractJsonSerializer(obj.GetType());
                obj = (T)serializer.ReadObject(memoryStream);
                return obj;
            }
        }

        internal static DateTime FromUnixTime(long unixTime)
        {
            var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            return epoch.AddSeconds(unixTime);
        }
    }
}
